<script setup lang="ts">
import { onLaunch, onShow, onHide, onPageNotFound, onExit } from '@dcloudio/uni-app';
import checkUpdate from '@/utils/check_update';
import { useUserStore } from '@/stores/user';
import cache from '@/utils/cache';
import { useMenu } from './stores/menu';
// #ifdef APP-PLUS
import setBedge from '@/utils/set_badge';
import { nextTick } from 'vue';
import showModal from '@/utils/modal';
// import { addShortcuts, removeAll } from '@/utils/shortcuts.js';
// #endif
// const shortcut = uni.requireNativePlugin('Ba-Shortcut');
let extraPage = '';
/**
 * 设置手机通知权限
 */
const setPermissionsInform = () => {
  // #ifdef APP-PLUS
  if (plus.os.name == 'Android') {
    // 判断是Android
    const main: any = plus.android.runtimeMainActivity();
    const pkName = main.getPackageName();
    const uid = main.getApplicationInfo().plusGetAttribute('uid');
    let NotificationManagerCompat: any = plus.android.importClass(
      'android.support.v4.app.NotificationManagerCompat',
    );
    //android.support.v4升级为androidx
    if (NotificationManagerCompat == null) {
      NotificationManagerCompat = plus.android.importClass(
        'androidx.core.app.NotificationManagerCompat',
      );
    }
    const areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();
    // 未开通‘允许通知’权限，则弹窗提醒开通，并点击确认后，跳转到系统设置页面进行设置
    if (!areNotificationsEnabled) {
      showModal({
        title: '通知权限开启提醒',
        content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
        showCancel: true,
        confirmText: '稍后设置',
        cancelText: '去设置',
        // success: function (res) {
        //   if (res.confirm) {

        //   }
        // },
      }).then(() => {
        const Intent: any = plus.android.importClass('android.content.Intent');
        const Build: any = plus.android.importClass('android.os.Build');
        //android 8.0引导
        if (Build.VERSION.SDK_INT >= 26) {
          const intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
          intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
          main.startActivity(intent); // 跳转到该应用的系统通知设置页
        } else if (Build.VERSION.SDK_INT >= 21) {
          //android 5.0-7.0
          const intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
          intent.putExtra('app_package', pkName);
          intent.putExtra('app_uid', uid);
          main.startActivity(intent); // 跳转到该应用的系统通知设置页
        }
      });
    }
  } else if (plus.os.name == 'iOS') {
    // 判断是ISO
    let isOn = undefined;
    let types = 0;
    const app = plus.ios.invoke('UIApplication', 'sharedApplication');
    const settings = plus.ios.invoke(app, 'currentUserNotificationSettings');
    if (settings) {
      types = settings.plusGetAttribute('types');
      plus.ios.deleteObject(settings);
    } else {
      types = plus.ios.invoke(app, 'enabledRemoteNotificationTypes');
    }
    plus.ios.deleteObject(app);
    isOn = 0 != types;
    if (isOn == false) {
      showModal({
        title: '通知权限开启提醒',
        content: '您还没有开启通知权限，无法接受到消息通知，请前往设置！',
        showCancel: true,
        confirmText: '稍后设置',
        cancelText: '去设置',
      }).then(() => {
        const app = plus.ios.invoke('UIApplication', 'sharedApplication');
        const setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
        plus.ios.invoke(app, 'openURL:', setting);
        plus.ios.deleteObject(setting);
        plus.ios.deleteObject(app);
      });
    }
  }
  // #endif
};

onLaunch(async () => {
  // #ifdef APP-PLUS

  setPermissionsInform();
  // plus.runtime.setBadgeNumber(-1);
  // plus.runtime.setBadgeNumber(0);
  // checkUpdate();
  uni.removeStorageSync('changeVersion1');
  uni.removeStorageSync('showModal');
  uni.removeStorageSync('installUpdate');
  plus.push.getClientInfoAsync(
    (info) => {
      console.log(info);
    },
    (err) => {
      console.log(err);
    },
  );
  // #ifdef  APP-PLUS
  // let res = removeAll();
  // res = addShortcuts([
  //   // {
  //   //   id: 'test', //必填,不能重复
  //   //   icon: plus.io.convertLocalFileSystemURL('/static/logo.png'), //本地图片,要使用平台绝对路径
  //   //   path: '/pages/test/test', //选填,跳转的页面路径
  //   //   shortLabel: '', //选填
  //   //   title: 'test页', //必填
  //   // },
  //   {
  //     id: 'barcode',
  //     icon: plus.io.convertLocalFileSystemURL('/static/barcode.png'), //本地图片,要使用平台绝对路径
  //     path: '/pages/pm/requirement/scan-code',
  //     shortLabel: '',
  //     title: '扫一扫',
  //   },
  // ]);
  // #endif
  // 个推消息
  let redirectUrl: string;
  let currentPage: any;
  let token: string;
  console.log(plus.push.getClientInfo().clientid);
  plus.push.addEventListener(
    'receive',
    function (msg: any) {
      const { content, payload } = msg;
      const payLoadStr = `${Object.keys(payload)
        .map((key) => {
          return `${key}=${payload[key]}`;
        })
        .join('&')}&method=custom`;
      plus.push.createMessage(content, payLoadStr, { title: content });
    },
    false,
  );

  plus.push.addEventListener(
    'click',
    (msg: any) => {
      console.log('redirectUrl', msg);
      const payload: any = {};
      msg.payload.split('&').forEach((item: any) => {
        const [k, v] = item.split('=');
        payload[k] = v;
      });

      // let { path } = payload;
      // Object.keys(payload).forEach((key) => {
      //   if (key !== 'path') {
      //     const val = payload[key];
      //     if (path.indexOf('?') === -1) {
      //       path = `${path}?${key}=${val}`;
      //     } else {
      //       path = `${path}&${key}=${val}`;
      //     }
      //   }
      // });

      let path = '';
      const pindex = msg.payload.indexOf('path=/pages');
      const p = msg.payload.substr(pindex);
      path = p.split('path=')[1];

      let rou = path;
      const queryInfo = rou?.split('?').length > 1 ? rou?.split('?')[1] : '';

      // nextTick(() => {
      const arr = queryInfo.split('&');
      const obj = { _source: 'message' };
      arr.map((item) => {
        const a = item.split('=');
        obj[a[0]] = a[1];
        return item;
      });
      const pa = rou?.split('?')[0];
      console.log(path, '123213');

      if (
        obj &&
        (obj.cusFlag == 3 || obj.cusFlg == 3) &&
        (pa == '/pages/pm/requirement/form' || pa == '/pages/pm/requirement/detail')
      ) {
        rou = path.replace('/requirement/form', '/gongying/form');
        rou = path.replace('/requirement/detail', '/gongying/form');
      }

      // 跳转逻辑
      redirectUrl = rou;
      token = cache.get('token');
      const pages = getCurrentPages();
      currentPage = pages[pages.length - 1];
      console.log('redirectUrl', redirectUrl);

      // 如果是自定义的 并且有没有token
      if (payload.method === 'custom' && !token) {
        uni.reLaunch({
          url: `/pages/index/login?redirect=${redirectUrl}`,
          success: () => {
            redirectUrl = '';
          },
        });
      } else if (redirectUrl.indexOf(currentPage.route) === -1) {
        // 尝试处理通知条详情折叠屏某些情况显示问题
        plus.screen.lockOrientation('portrait-primary');
        setTimeout(() => {
          uni.navigateTo({
            url: redirectUrl,
            complete: () => {
              setTimeout(() => {
                plus.screen.unlockOrientation();
              }, 800);
            },
          });
        }, 350);
      }
      //
      // plus.push.clear();
    },
    false,
  );

  // #endif
  const userStore = useUserStore();
  userStore.getUser();
  const menu = useMenu();
  menu.getMenuList().then((res) => {
    // 需要菜单获取后的操作逻辑在这里执行，例如需要直接访问app某个页面需要获取菜单id时
    // console.log(res);
  });
});
onShow(async (options) => {
  // #ifdef APP-PLUS
  uni.setStorageSync('isHide', 0);
  // uni.setStorageSync('changeVersion', 0);
  if (uni.getStorageSync('installUpdate')) {
    const installUpdate = function (resource: string): Promise<PlusRuntimeWidgetInfo> {
      return new Promise((resolve, reject) => {
        plus.runtime.install(
          resource,
          { force: true },
          function onSuccess(widgetInfo) {
            console.log(widgetInfo);
            console.log('安装成功');
            uni.removeStorageSync('installUpdate');
            uni.removeStorageSync('changeVersion1');
            resolve(widgetInfo);
          },
          function onError(error) {
            uni.removeStorageSync('changeVersion1');
            uni.removeStorageSync('installUpdate');
            reject(error);
            console.log('安装失败：', error);
          },
        );
      });
    };
    installUpdate(uni.getStorageSync('installUpdate'));
  }
  // 检测更新
  // checkUpdate();
  if (plus.runtime.arguments) {
    const menu = useMenu();
    if (!menu.menuList) {
      await menu.getMenuList();
    }
    try {
      const extra = JSON.parse(plus.runtime.arguments);
      if (extra?.page && extra.page !== extraPage) {
        extraPage = extra?.page;
        setTimeout(() => {
          uni.navigateTo({
            url: extra.page,
          });
        }, 500);
      }
    } catch (e) {
      console.log(e);
    }
  }

  /**
   * 点击通知栏跳转
   */
  const main = plus.android.runtimeMainActivity();
  const intent = main.getIntent();
  const path = plus.android.invoke(intent, 'getStringExtra', 'path'); // list 里面的 path
  plus.android.invoke(intent, 'removeExtra', 'path');
  plus.android.autoCollection(intent);

  //根据 path路径 进行跳转
  if (path === null) return;
  if (!cache.get('token')) {
    nextTick(() => {
      uni.redirectTo({
        url: '/pages/login/login?redirect=' + path,
      });
    });
  } else {
    nextTick(() => {
      uni.navigateTo({
        url: path,
      });
    });
  }

  // #endif
});
onHide(() => {
  console.log('App Hide');
  uni.setStorageSync('isHide', 1);
  // #ifdef APP-PLUS
  setBedge();
  // #endif
});
onExit(() => {
  // #ifdef APP-PLUS
  setBedge();
  // #endif
});
onPageNotFound(() => {
  console.log('onPageNotFound');
});
</script>

<style lang="scss">
@import '@/static/css/icon.css';
/* stylelint-disable selector-type-no-unknown */
button::after {
  border: none;
}

swiper,
scroll-view {
  flex: 1;
  height: 100%;
  overflow: hidden;
}

image {
  width: 100%;
  height: 100%;
  vertical-align: middle;
}

// 单行省略，优先使用 unocss: text-ellipsis
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

// 两行省略
.ellipsis-2 {
  display: -webkit-box;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

// 三行省略
.ellipsis-3 {
  display: -webkit-box;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
</style>
